<template>
  <BaseMainSlot :show-tab="false" :show-btn-box="false">
    <template v-slot:search-box>
      <SearchForm :formConfig="formConfig" :formData="searchlist" @search="search"></SearchForm>
    </template>
    <template v-slot:btn-box>
      <ActionBar
        :page-no="76"
        :add-active="addActive"
        :del-active="delActive"
        :has-edit="false"
        :has-save="false"
        :has-cancel="false"
        @add="add"
        @del="del"
      />
    </template>
    <template v-slot:table-box>
      <Table @sortChange="changeTableSort" :propList="tableColumn" v-loading="loading"
        :listData="tableData" @handleSelectionChange="handleSelectionChange">
        <template v-slot:operation="{ row }">
          <template v-if="!row.index">
            <el-button
              v-if="judgePermission(76, 'edit')"
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="edit(row)"
            >
              <i class="el-icon-edit-outline"></i> 修改
            </el-button>
            <el-button
              v-if="judgePermission(76, 'delete')"
              class="text-btn-cursor cursor-delete"
              type="text"
              size="small"
              @click="handleDelete(row.stordocNo)"
            >
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </template>
        <template v-slot:onHandQuantity="{ row, item }">
          <template v-if="!row.index">
            {{ row[`${item.prop}`] }}
            {{ row[`${item.porpObj}`] && row[`${item.porpObj}`][`${item.porpName}`] }}
          </template>
        </template>
        <template v-slot:other="{ row, item }">
          <template v-if="!row.index">
            {{ item.porpObj
              ? row[`${item.porpObj}`] && row[`${item.porpObj}`][`${item.porpName}`]
              : row[`${item.prop}`] || "——" }}
          </template>
        </template>
      </Table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:dialog>
      <el-dialog :title="titleText" :visible.sync="dialogFormVisible">
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          :rules="rules"
          class="el-form"
        >
          <el-form-item
            v-for="item,index in formDatalists"
            :key="index"
            :label="item.name + ':'"
            :prop="item.selectValue || item.prop"
            class="w50p"
            :rules="[
              { required: item.required, message: item.name + '不能为空', trigger: 'change'}
            ]"
          >
            <el-input
              v-if="item.type === 'input'"
              v-model="formData[ `${item.prop}`]"
              :placeholder="'请输入' + item.name"
              clearable
            />
            <el-select
              v-if="item.type === 'Select'"
              v-model="formData[ `${item.selectValue}`]"
              filterable
              :placeholder="'请选择' + item.name"
              clearable
            >
              <el-option
                v-for="items,indexs in item.typeObj.list"
                :key="indexs"
                :label="items.name"
                :value="items.value"
              />
            </el-select>
            <el-date-picker
              v-if="item.type === 'TimePicker'"
              v-model="formData[ `${item.prop}`]"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="'选择' + item.name"
            />
          </el-form-item>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
          <el-button
            class="zh-button-two"
            type="primary"
            @click="save('formData')"
          >保 存</el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import SearchForm from '@/components/searchForm';
import Table from '@/components/table/table.vue';
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot";
import { mymixin } from "@/utils/mixins";
import { mapGetters } from "vuex";

import InventoryApi from "@/api/livestock-manage/storage-manage/inventory-changes";
import personApi from "@/api/livestock-manage/personnel-cost-mansge/staff-manage";

export default {
  name: "SheepInformation",
  components: { SearchForm, Table, ActionBar, Pagination, BaseMainSlot },
  mixins: [mymixin],
  data() {
    return {
      searchlist: {},
      tableColumn: [],
      formConfig: [
        {
          label: '单据类型',
          prop: 'orderType',
          type: 'select',
          options: [
            {
              name: "出库",
              value: "出库"
            },
            {
              name: "入库",
              value: "入库"
            },
            {
              name: "盘盈",
              value: "盘盈"
            },
            {
              name: "盘亏",
              value: "盘亏"
            }
          ],
          optionKey: { label: 'name', value: 'value' },
        },
        {
          label: '单据号',
          prop: 'orderNo',
          type: 'input',
        },
        {
          label: '行号',
          prop: 'batchNo',
          type: 'input',
        },
      ],
      selectedStaffList: [],
      // selectValue 用于传递select的编号
      formDatalists: [
        {
          type: "Select", // input Select Checkbox TimePicker
          prop: "orderType",
          selectValue: "orderType",
          typeObj: {
            list: [
              {
                name: "出库",
                value: "出库"
              },
              {
                name: "入库",
                value: "入库"
              },
              {
                name: "盘盈",
                value: "盘盈"
              },
              {
                name: "盘亏",
                value: "盘亏"
              }
            ]
          },
          name: "单据类型",
          required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "orderNo",
          selectValue: "",
          typeObj: {},
          name: "单据号",
          required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "batchNo",
          typeObj: {},
          name: "行号",
          required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "phone",
          porpObj: "batchFile",
          porpName: "lotNumber",
          selectValue: "",
          typeObj: {},
          name: "批号",
          required: true,
          notSearch: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "materialName",
          porpObj: "material",
          porpName: "materialName",
          selectValue: "",
          typeObj: {},
          name: "物料",
          required: true,
          notSearch: true
        },
        // {
        //   type: "input", // input Select Checkbox TimePicker
        //   prop: "produceDate",
        //   porpObj: "batchFile",
        //   porpName: "produceDate",
        //   typeObj: {},
        //   name: "生产日期",
        //   required: true,
        //   notSearch: true
        // },
        // {
        //   type: "input", // input Select Checkbox TimePicker
        //   prop: "expirationDate",
        //   porpObj: "batchFile",
        //   porpName: "expirationDate",
        //   selectValue: "enableStatus",
        //   typeObj: {},
        //   name: "失效日期",
        //   required: true,
        //   notSearch: true
        // },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "variation",
          porpObj: "castUnit",
          porpName: "symbol",
          selectValue: "",
          typeObj: {},
          name: "变化量",
          required: false
          // notSearch: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "onHandQuantity",
          porpObj: "cUnit",
          porpName: "symbol",
          selectValue: "",
          typeObj: {},
          name: "主数量",
          required: false
          // notSearch: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "vchangerate",
          selectValue: "",
          typeObj: {},
          name: "换算率",
          required: true
          // notSearch: true
        }
      ]
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  created() {
    let list = []
    this.formDatalists.map(el => {
      let obj = {
        prop: el.prop, label: el.name, minWidth: '140px', porpObj: el.porpObj, porpName: el.porpName
      }
      if (['onHandQuantity', 'variation'].includes(el.prop)) {
        obj.slotName = 'onHandQuantity'
      } else {
        obj.slotName = 'other'
      }
      list.push(obj)
    })
    // list.push({ prop: 'operation', label: '操作', slotName: 'operation', width: '150' })
    this.tableColumn = list

    this.search();
    this.getPerson();
  },
  methods: {
    // 获取记录人列表
    getPerson() {
      personApi.getStaffListByCondition().then(res => {
        if (res.code === 1) {
          let list = [];
          this.personList = res.data || [];
          res.data.forEach(item => {
            list.push({
              name: item.person.name,
              value: item.personNo
            });
          });
          this.formDatalists.forEach((item, index) => {
            if (item.prop === "personName") {
              this.$set(this.formDatalists[index].typeObj, "list", list);
            }
          });
        }
      });
    },
    getTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: this.searchlist
      };
      InventoryApi.pageQuery(params).then(res => {
        this.loading = false;
        let data = res.data;
        // 赋值总条数
        if (data) {
          this.totalSize = data.totalElements;
          // 赋值数组
          this.tableData = data.content;
          this.addblankmet();
          this.resetActionBar();
        }
      });
    },
    handleSelectionChange(list) {
      this.selectedStaffList = [];
      this.selectedStaffList = list.map(item => item.stordocNo);
      if (this.selectedStaffList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    delmessage() {
      InventoryApi.numberBatchDel({ noList: this.selectedStaffList }).then(
        res => {
          if (res.code === 1) {
            this.$message.success(res.msg);
            this.search();
          } else {
            this.$message.warning(res.msg || "删除失败");
          }
        }
      );
    },
    handleDelete(val) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          InventoryApi.numberDel(val).then(res => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.search();
            } else {
              this.$message.warning(res.msg || "删除失败");
            }
          });
        })
        .catch(() => {});
    },
    add() {
      this.formData = {};
      this.nowChanceStau = "add";
      this.titleText = "添加仓库";
      this.addActive = false;
      this.delActive = false;
      this.dialogFormVisible = true;
    },
    edit(row) {
      this.formData = { ...row };
      this.nowChanceStau = "edit";
      this.titleText = "修改仓库";
      this.dialogFormVisible = true;
      this.addActive = true;
      this.delActive = false;
    },
    save(formData) {
      console.log(this.formData);
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            let formData = { ...this.formData };
            InventoryApi.edit(formData).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "修改成功！");
                this.dialogFormVisible = false;
                this.search();
                this.$refs[formData].resetFields();
              } else {
                this.$message.error(res.msg || "修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            let person = { ...this.formData };
            InventoryApi.add(person).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "新增成功！");
                this.dialogFormVisible = false;
                this.search();
                this.$refs[formData].resetFields();
              } else {
                this.$message.error(res.msg || "新增失败！");
              }
            });
          }
        } else {
          return false;
        }
      });
    }
  }
};
</script>
<style scoped lang="scss">
@import "~@/styles/variables.scss";
</style>
